package ru.ipo.dces.plugins.admin;


import info.clearthought.layout.TableLayout;
import ru.ipo.dces.client.Controller;
import ru.ipo.dces.client.Localization;
import ru.ipo.dces.client.messages.PopupMessageType;
import ru.ipo.dces.clientservercommunication.AcceptedResponse;
import ru.ipo.dces.clientservercommunication.ContestDescription;
import ru.ipo.dces.clientservercommunication.StopContestRequest;
import ru.ipo.dces.clientservercommunication.UserDescription;
import ru.ipo.dces.pluginapi.Plugin;
import ru.ipo.dces.pluginapi.PluginEnvironment;
import ru.ipo.dces.plugins.admin.components.ContestInformationPanel;
import ru.ipo.dces.server.ServerFailReason;
import ru.ipo.dces.utils.ResponseHandler;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LogoutPluginV2 extends JPanel implements Plugin {

    private JButton logoutButton = new JButton("Выход");
    private JButton refreshProblemsButton = new JButton("Обновить");
    private JButton refreshPluginsButton = new JButton("Обновить");
    private JLabel stopContestLabel = new JLabel("Закончить соревнование досрочно");
    private JButton stopContestButton = new JButton("Закончить");
    private ContestInformationPanel contestInformationPanel = new ContestInformationPanel();
    private int separatorGap = 5;

    public LogoutPluginV2(PluginEnvironment env) {
        setupUI();
        env.setTitle(Localization.getAdminPluginName(LogoutPluginV2.class));
        addListeners();
    }

    private void addListeners() {
        logoutButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (JOptionPane.showConfirmDialog(null, "Действительно выйти?",
                        "Подтверждение", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
                    Controller.logout();
            }
        });
        refreshProblemsButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (Controller.getContestConnection().getUser().userType != UserDescription.UserType.Participant) {
                    JOptionPane.showMessageDialog(null, "Только участники могут обновлять список задач");
                    return;
                }

                try {
                    Controller.getClientDialog().clearLeftPanel();
                    //the first plugin will be selected after this call
                    Controller.refreshParticipantInfo(true, false);
                    JOptionPane.showMessageDialog(null, "Условия успешно обновлены");
                } catch (Exception ee) {
                    JOptionPane.showMessageDialog(null, "Не удалось обновить условия");
                    Controller.getClientDialog().initialState();
                }
            }
        });
        refreshPluginsButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (Controller.getContestConnection().getUser().userType == UserDescription.UserType.SuperAdmin) {
                    JOptionPane.showMessageDialog(null, "Супер администратор не может обновить модули");
                    return;
                }

                try {
                    Controller.getClientDialog().clearLeftPanel();
                    //the first plugin will be selected after this call
                    Controller.refreshParticipantInfo(false, true); //refresh = false
                    JOptionPane.showMessageDialog(null, "Модули задач успешно обновлены");
                } catch (Exception ee) {
                    JOptionPane.showMessageDialog(null, "Не удалось обновить модули задач");
                    Controller.getClientDialog().initialState();
                }
            }
        });
        stopContestButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (JOptionPane.showConfirmDialog(null, "Действительно выйти?", "Подтверждение",
                        JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

                    ResponseHandler<AcceptedResponse> handler = new ResponseHandler<AcceptedResponse>() {
                        @Override
                        public void success(AcceptedResponse response) {
                            Controller.showPopupMessage("Соревнование успешно остановлено", PopupMessageType.Info);
                        }

                        @Override
                        public void fail(ServerFailReason exception) {
                        }
                    };

                    StopContestRequest r = new StopContestRequest();
                    r.sessionID = Controller.getContestConnection().getSessionID();
                    Controller.doRequest(r, handler, "Остановка соревнования");
                }
            }
        });
    }

    private void setStopContestControlsVisible(boolean visible) {
        stopContestLabel.setVisible(visible);
        stopContestButton.setVisible(visible);
    }

    @Override
    public JPanel getPanel() {
        return this;
    }

    @Override
    public void activate() {
        ContestDescription cd = Controller.getContestConnection().getContest();
        boolean visible = cd != null && cd.contestTiming != null && cd.contestTiming.selfContestStart;
        setStopContestControlsVisible(visible);
        if (!Controller.isContestUnknownMode())
            contestInformationPanel.setContest(cd);
    }

    @Override
    public void deactivate() {
        // do nothing
    }

    private void setupUI() {
        int verticalGap = 10;
        setLayout(new TableLayout(
                new double[]{verticalGap, TableLayout.FILL, 275, TableLayout.PREFERRED, TableLayout.FILL, verticalGap},
                new double[]{verticalGap, TableLayout.PREFERRED, verticalGap, TableLayout.PREFERRED, TableLayout.FILL,
                        TableLayout.PREFERRED, verticalGap}
        ));
        add(getContestInfoPanel(), "2, 1");
        add(getStopPanel(), "2, 3, 3, 3");
        add(getRefreshPanel(), "1, 5, 4, 5");
    }

    private JPanel getContestInfoPanel() {
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new TableLayout(
                new double[]{TableLayout.PREFERRED},
                new double[]{TableLayout.PREFERRED, separatorGap, TableLayout.PREFERRED}
        ));
        if (Controller.isContestUnknownMode())
            infoPanel.add(new JLabel("Вы вошли как суперадминистратор"), "0, 2");
        else {
            infoPanel.add(new JLabel("Вы участник соревнования"), "0, 0");
            contestInformationPanel.setPreferredSize(new Dimension(275, 180));
            infoPanel.add(contestInformationPanel, "0, 2");
        }
        return infoPanel;
    }

    private JPanel getStopPanel() {
        JPanel stopPanel = new JPanel();
        stopPanel.setLayout(new TableLayout(
                new double[]{TableLayout.PREFERRED, separatorGap, TableLayout.PREFERRED},
                new double[]{TableLayout.PREFERRED, separatorGap, TableLayout.PREFERRED}
        ));
        stopPanel.add(new JLabel("Перейти к другому соревнованию"), "0, 0");
        stopPanel.add(logoutButton, "2, 0");
        stopPanel.add(stopContestLabel, "0, 2");
        stopPanel.add(stopContestButton, "2, 2");
        return stopPanel;
    }

    private JPanel getRefreshPanel() {
        JPanel refreshPanel = new JPanel();
        refreshPanel.setLayout(new TableLayout(
                new double[]{TableLayout.FILL, TableLayout.PREFERRED, separatorGap, TableLayout.PREFERRED},
                new double[]{TableLayout.PREFERRED, separatorGap, TableLayout.PREFERRED}
        ));
        refreshPanel.add(new JLabel("Обновить условия задачи"), "1, 0");
        refreshPanel.add(refreshProblemsButton, "3, 0");
        refreshPanel.add(new JLabel("Обновить модули задач"), "1, 2");
        refreshPanel.add(refreshPluginsButton, "3, 2");
        return refreshPanel;
    }
}
